package com.zbw.weightlibrary.WeightSub;

import android.content.Context;
import android.hardware.usb.UsbManager;

import com.zbw.weightlibrary.Connector.BaseControlImpl;
import com.zbw.weightlibrary.Connector.IinfoCallback;
import com.zbw.weightlibrary.Connector.WeightData;
import com.zbw.weightlibrary.Util.ThreadPoolManager;

import java.nio.ByteBuffer;
import java.util.ArrayList;

import tw.com.prolific.driver.pl2303.PL2303Driver;

/**
 * 作者 ：Wesley
 * 时间 ：2019-12-28 15:57
 * 这个类是干嘛的？：WeightUsbToSerial
 * usb口连接串口称
 */
public class WeightUsbToSerial extends BaseControlImpl {
    private static final String ACTION_USB_PERMISSION = "com.prolific.pl2303hxdsimpletest.USB_PERMISSION";
    private final Context mContext;
    private final IinfoCallback mCallback;
    private final int myBaudrate; //串口电子称波特率baudrate
    private PL2303Driver mSerial;
    private PL2303Driver.BaudRate mBaudrate;


    public WeightUsbToSerial(Context context, IinfoCallback callback, WeightData data) {
        super(callback);
        mContext = context;
        mCallback = callback;
        myBaudrate = data.getBaudrate();
    }

    @Override
    public void bleConnect() {
        Connect(myBaudrate);
    }

    @Override
    public void bleDisconnect() {
        if (mSerial != null) {
            mSerial.end();
            mSerial = null;
        }
    }

    @Override
    public void getWeight() {
        ReadWeight();
    }

    @Override
    public void stopWeight() {
        ReadWeight = false;
    }

    @Override
    public void clearTare() {

    }

    @Override
    public void tare() {

    }

    @Override
    public void zero() {

    }

    private void Connect(final int myBaudrate){
        ThreadPoolManager.getInstance().executeTask(new Runnable() {
            @Override
            public void run() {
                try {
                    //初始化
                    mSerial = new PL2303Driver((UsbManager) mContext.getSystemService(Context.USB_SERVICE), mContext, ACTION_USB_PERMISSION);
                    if (!mSerial.PL2303USBFeatureSupported()) {
                        mCallback.onConnect("连接失败！", false);
                        mSerial = null;
                        return;
                    }
                    Thread.sleep(100);
                    if (mSerial.isConnected()) {
                        switch (myBaudrate) {
                            case 19200:
                                mBaudrate = PL2303Driver.BaudRate.B19200;
                                break;
                            case 115200:
                                mBaudrate = PL2303Driver.BaudRate.B115200;
                                break;
                            default:
                                mBaudrate = PL2303Driver.BaudRate.B9600;
                                break;
                        }
                        //波特率初始化
                        if(mSerial.InitByBaudRate(mBaudrate, 700)){
                            mCallback.onConnect("连接成功！", true);
                        }
                    } else {
                        mCallback.onConnect("连接失败！", false);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    mCallback.onConnect("连接失败！", false);
                }
            }
        });
    }

    private void ReadWeight(){
        ReadWeight = true;
        mRecvData = new ArrayList<>();
        ValueSize = 0;
        ThreadPoolManager.getInstance().executeTask(new Runnable() {
            @Override
            public void run() {
                try {
                    while (mSerial != null && ReadWeight) {
                        final byte[] rbuf = new byte[128];
                        if(!mSerial.isConnected()) return;
                        int len = mSerial.read(rbuf);
                        if(len<0) return;

                        if (len > 0) {
                            ByteBuffer bb = ByteBuffer.allocate(len);
                            bb.put(rbuf, 0, len);
                            postOnReceived(bb.array());
                        }
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    mCallback.onDisconnect("获取重量失败！"+e.getMessage(),false);
                }
            }
        });
    }

}
